package com.hotelManager.www.servlet;

import com.google.gson.JsonObject;
import com.hotelManager.www.config.GsonConfig;
import com.hotelManager.www.controller.TouristController;
import com.hotelManager.www.po.User;
import com.hotelManager.www.service.RoomTypeService;
import com.hotelManager.www.service.ShopService;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.po.RoomType;
import com.hotelManager.www.common.Result;
import com.hotelManager.www.common.ResultCode;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.google.gson.Gson;



/**
 * 游客端Servlet
 * 处理游客相关的HTTP请求，包括注册、浏览店铺、搜索店铺、查看店铺详情等功能
 * 使用@WebServlet注解映射URL路径"/tourist/*"
 */
@WebServlet("/tourist/*")
public class TouristServlet extends HttpServlet {
    // 创建TouristController实例，用于处理业务逻辑
    private final TouristController touristController = new TouristController();
    private final Gson gson = GsonConfig.getGson();
    private final RoomTypeService roomTypeService = new RoomTypeService();
    private final ShopService shopService = new ShopService();
    /**
     * 处理GET请求
     * 主要处理查询操作，如浏览店铺、搜索店铺、查看店铺详情等
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        String path = req.getPathInfo();
        System.out.println("[TouristServlet] 收到GET请求: " + path);

        String pathInfo = req.getPathInfo();
        System.out.println("请求路径: " + pathInfo);
        if (pathInfo == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "路径不能为空")));
            return;
        }// 调试日志

        try {
            switch (pathInfo) {
                case "/shops":
                    // 处理浏览店铺请求
                    handleBrowseShops(req, resp);
                    break;
                case "/shops/detail":
                    // 处理获取店铺详情请求
                    handleGetShopDetail(req, resp);
                    break;
                case "/shops/roomTypes":
                    // 处理获取店铺房型请求
                    handleGetShopRoomTypes(req, resp);
                    break;
                default:
                    // 未知操作，返回错误信息
                    resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "未知操作").toJson());
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "参数格式错误").toJson());
        } catch (Exception e) {
            resp.getWriter().write(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "服务器内部错误").toJson());
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        String path = req.getPathInfo();
        System.out.println("[TouristServlet] 收到post请求: " + path);

        String pathInfo = req.getPathInfo();
        System.out.println("请求路径: " + pathInfo);
        if (pathInfo == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "路径不能为空")));
            return;
        }// 调试日志

        try {
            switch (pathInfo) {
                case "/shops/search":
                    // 处理搜索店铺请求
                    handleSearchShops(req, resp);
                    break;
                default:
                    // 未知操作，返回错误信息
                    resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "未知操作").toJson());
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "参数格式错误").toJson());
        } catch (Exception e) {
            resp.getWriter().write(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "服务器内部错误").toJson());
        }
    }


    /**
     * 处理浏览店铺请求
     * 支持分页查询
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleBrowseShops(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 获取分页参数，设置默认值
            int page = req.getParameter("page") != null ? Integer.parseInt(req.getParameter("page")) : 1;
            int pageSize = req.getParameter("limit") != null ? Integer.parseInt(req.getParameter("limit")) : 8;

            // 调用控制器获取店铺列表
            Map<String, Object> shops = touristController.browseShops(page, pageSize);

            // 返回店铺列表
            resp.getWriter().write(Result.success(shops).toJson());
        } catch (NumberFormatException e) {
            // 参数格式错误
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "分页参数格式错误").toJson());
        }
    }

    /**
     * 处理搜索店铺请求
     * 支持根据关键词搜索，并支持分页
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleSearchShops(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 设置请求和响应的字符编码
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");

            // 读取JSON数据
            StringBuilder buffer = new StringBuilder();
            try (BufferedReader reader = req.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
            }

            // 解析JSON数据
            JsonObject jsonObject = gson.fromJson(buffer.toString(), JsonObject.class);
            String keyword = jsonObject.has("keyword") ? jsonObject.get("keyword").getAsString() : "";
            int page = jsonObject.has("page") ? jsonObject.get("page").getAsInt() : 1;
            int pageSize = jsonObject.has("pageSize") ? jsonObject.get("pageSize").getAsInt() : 10;

            // 调用控制器搜索店铺
            Map<String, Object> shops = touristController.searchShops(keyword, page, pageSize);

            // 返回搜索结果
            resp.getWriter().write(Result.success(shops).toJson());
        } catch (NumberFormatException e) {
            // 参数格式错误
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "分页参数格式错误").toJson());
        } catch (Exception e) {
            // 处理其他异常
            resp.getWriter().write(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "服务器内部错误").toJson());
        }
    }

    /**
     * 处理获取店铺详情请求
     * 同时会更新店铺的浏览量
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleGetShopDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String shopIdStr = req.getParameter("shopId");
        System.out.println("[TouristServlet] 请求店铺详情, shopId=" + shopIdStr);
        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            System.out.println("[TouristServlet] shopId为空");
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空").toJson());
            return;
        }
        try {
            int shopId = Integer.parseInt(shopIdStr);
            Shop shop = touristController.getShopDetail(shopId);
            if (shop == null) {
                System.out.println("[TouristServlet] 未找到店铺, shopId=" + shopId);
                resp.getWriter().write(Result.failure(ResultCode.NOT_FOUND, "店铺不存在").toJson());
                return;
            }
            List<RoomType> roomTypes = roomTypeService.getRoomTypesByShopId(shopId);
            System.out.println("[TouristServlet] 查询到房型数量: " + (roomTypes == null ? "null" : roomTypes.size()));
            Map<String, Object> data = new HashMap<>();
            data.put("shop", shop);
            data.put("roomTypes", roomTypes);
            resp.getWriter().write(Result.success(data, "获取店铺详情成功").toJson());
        } catch (NumberFormatException e) {
            System.out.println("[TouristServlet] shopId格式错误: " + shopIdStr);
            resp.getWriter().write(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确").toJson());
        } catch (Exception e) {
            System.out.println("[TouristServlet] 查询店铺详情异常: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "服务器内部错误").toJson());
        }
    }
    /**
     * 处理获取店铺房型请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleGetShopRoomTypes(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String shopIdStr = req.getParameter("shopId");
        System.out.println("[TouristServlet] 请求房型列表, shopId=" + shopIdStr);

        try {
            if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
                System.out.println("[TouristServlet] shopId为空");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
                return;
            }

            int shopId = Integer.parseInt(shopIdStr);
            System.out.println("[TouristServlet] 解析shopId=" + shopId);

            // 先检查店铺是否存在
            Shop shop = shopService.findById(shopId);
            System.out.println("[TouristServlet] 查询店铺结果: " + shop);

            if (shop == null) {
                System.out.println("[TouristServlet] 店铺不存在");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "店铺不存在")));
                return;
            }

            // 获取房型列表
            List<RoomType> roomTypes = roomTypeService.getRoomTypesByShopId(shopId);
            System.out.println("[TouristServlet] 查询到房型数量: " + (roomTypes == null ? "null" : roomTypes.size()));

            if (roomTypes == null) {
                System.out.println("[TouristServlet] 房型列表为null");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取房型列表失败")));
                return;
            }

            if (roomTypes.isEmpty()) {
                System.out.println("[TouristServlet] 房型列表为空");
                resp.getWriter().write(gson.toJson(Result.success(new ArrayList<>(), "该店铺暂无房型")));
                return;
            }

            System.out.println("[TouristServlet] 成功获取到" + roomTypes.size() + "个房型");
            resp.getWriter().write(gson.toJson(Result.success(roomTypes, "获取房型列表成功")));

        } catch (NumberFormatException e) {
            System.out.println("[TouristServlet] shopId格式错误: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        } catch (Exception e) {
            System.out.println("[TouristServlet] 获取房型数据出错: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取房型列表失败：" + e.getMessage())));
        }
    }
}

